import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        title: '登录 - 云盘系统'
      }
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: Dashboard,
      meta: {
        title: '我的云盘',
        requiresAuth: true
      }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log('Route change:', { to, from })
  
  const token = localStorage.getItem('token')
  console.log('Current token:', token)

  // 设置页面标题
  document.title = to.meta.title || '云盘系统'

  // 如果访问的是登录页
  if (to.path === '/login') {
    if (token) {
      console.log('Already logged in, redirecting to dashboard')
      next('/dashboard')
    } else {
      console.log('Not logged in, allowing access to login page')
      next()
    }
    return
  }

  // 如果路由需要认证
  if (to.meta.requiresAuth) {
    if (!token) {
      console.log('Auth required but no token, redirecting to login')
      next('/login')
    } else {
      console.log('Auth required and has token, allowing access')
      next()
    }
    return
  }

  // 其他情况
  next()
})

export default router